package com.insight.modules.ngalain.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.system.vo.DictModel;
import com.insight.common.system.vo.LoginUser;
import com.insight.modules.ngalain.service.NgAlainService;
import com.yuanqiao.insight.acore.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sys/ng-alain")
public class NgAlainController {

    @Autowired
    private NgAlainService ngAlainService;

    @Autowired
    private ISysDictService sysDictService;

    /**
     * 获取当前登录用户的应用数据，包括用户信息、菜单和应用基本信息
     *
     * @param request HTTP请求，主要用于获取token
     * @return 封装的用户信息、菜单和应用信息的JSON对象
     * @throws Exception 可能出现的异常
     */
    @RequestMapping(value = "/getAppData")
    @ResponseBody
    public JSONObject getAppData(HttpServletRequest request) throws Exception {
        // 从请求头获取Token
        String token = request.getHeader("X-Access-Token");

        JSONObject j = new JSONObject();

        // 获取当前登录用户信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 构建用户信息对象
        JSONObject userObjcet = new JSONObject();
        userObjcet.put("name", user.getUsername());
        userObjcet.put("avatar", user.getAvatar());
        userObjcet.put("email", user.getEmail());
        userObjcet.put("token", token);
        j.put("user", userObjcet);

        // 获取用户对应菜单数据
        try {
            j.put("menu", ngAlainService.getMenu(user.getUsername()));
        } catch (Exception e) {
            log.error("获取用户菜单失败，用户名: {}", user.getUsername(), e);
            j.put("menu", new ArrayList<>()); // 返回空菜单防止前端出错
        }

        // 构建应用信息
        JSONObject app = new JSONObject();
        app.put("name", "jeecg-boot-angular");
        app.put("description", "jeecg+ng-alain整合版本");
        j.put("app", app);

        return j;
    }

    /**
     * 根据字典编码获取字典项列表
     *
     * @param dictCode 字典编码
     * @return 字典项的列表，每个项包含value和label字段
     */
    @RequestMapping(value = "/getDictItems/{dictCode}", method = RequestMethod.GET)
    public Object getDictItems(@PathVariable String dictCode) {
        log.info(" dictCode : " + dictCode);
        Result<List<DictModel>> result = new Result<>();
        List<DictModel> ls = null;
        try {
            if (StringUtils.isEmpty(dictCode)){
                return result;
            }
            // 查询字典项
            ls = sysDictService.queryDictItemsByCode(dictCode);
            result.setSuccess(true);
            result.setResult(ls);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
            return result;
        }

        // 将字典项转换成符合前端格式的JSON对象列表
        List<JSONObject> dictlist = new ArrayList<>();
        for (DictModel l : ls) {
            JSONObject dict = new JSONObject();
            try {
                // 尝试将value转换成整数类型
                dict.put("value", Integer.parseInt(l.getValue()));
            } catch (NumberFormatException e) {
                // 非数字则原样存储字符串
                dict.put("value", l.getValue());
            }
            dict.put("label", l.getText());
            dictlist.add(dict);
        }
        return dictlist;
    }

    /**
     * 根据指定数据库表、键和值字段获取字典项
     *
     * @param table 表名
     * @param key   键字段名
     * @param value 值字段名
     * @return 字典项列表
     */
    @RequestMapping(value = "/getDictItemsByTable/{table}/{key}/{value}", method = RequestMethod.GET)
    public Object getDictItemsByTable(@PathVariable String table,
                                      @PathVariable String key,
                                      @PathVariable String value) {
        return this.ngAlainService.getDictByTable(table, key, value);
    }
}

